<template>
	<div>
		<Modal v-model="modal.setting" title="运费模板项设置" :mask-closable="false" width="1020">
			<div v-for="(expressItem, index) in expressJson" :key="index">
				<div style="margin-bottom: 10px;">
					<Tag color="error">{{expressItem.expressCompany}}</Tag>
				</div>
				<div style="margin-bottom: 20px;" v-for="(expressData, dataIdx) in expressItem.expressData" :key="dataIdx">
					<div v-if="!onlyView">
						<Tag v-for="(expressArea, areaIdx)  in expressData.area" :key="areaIdx" color="primary" :name="expressArea.province"
						 closable @on-close="removeProvince(expressArea.id)">{{expressArea.province}}</Tag>
						<Button icon="ios-add" type="dashed" size="small" style="margin-right: 10px;" @click="showAddProvince(expressItem, expressData.data)">添加省</Button>
						<Button icon="ios-remove" type="error" size="small" @click="removeAllProvince(expressData.area)">删除所有省</Button>
					</div>
					<div v-else>
						<Tag v-for="(expressArea, areaIdx)  in expressData.area" :key="areaIdx" color="primary" :name="expressArea.province">{{expressArea.province}}</Tag>
					</div>
					<div>
						<Tag>是否包邮：{{expressData.data.expressFreeVal}}</Tag>
						<Tag>规格：{{expressData.data.expressSpec}}</Tag>
						<Tag>运费：{{expressData.data.expressFee}}</Tag>
						<Tag>递增：{{expressData.data.incrementSpec}}</Tag>
						<Tag>递增费用：{{expressData.data.incrementFee}}</Tag>
						<Tag>达此金额包邮：{{expressData.data.freeMaxPayment}}</Tag>
						<Tag>达此数量包邮：{{expressData.data.freeCondition}}</Tag>
						<Button v-if="!onlyView" icon="ios-create-outline" type="dashed" size="small" @click="showEdit(expressItem.expressCompany, expressData)">修改</Button>
					</div>
				</div>
			</div>
			<Button v-if="!onlyView" icon="ios-add" type="success" size="small" @click="showAddExpressItem">新建模板项</Button>
			<div slot="footer">
				<Button type="text" size="large" @click="closeSetting">关闭</Button>
			</div>
		</Modal>
		<Modal v-model="modal.edit" title="修改模板数据" :mask-closable="false" width="1020" @on-visible-change="changeModalVisibleResetForm('editForm', $event)">
			<Form ref="editForm" :model="form" :label-width="120" :rules="validateRules">
				<Row>
					<i-col span="12">
						<FormItem label="是否包邮" prop="expressFree">
							<Select v-model="form.expressFree" placeholder="是否包邮" filterable clearable>
								<Option v-for="(option, index) in expressFreeSelect" :value="option.value" :key="index">{{option.displayValue}}</Option>
							</Select>
						</FormItem>
						
					</i-col>
					<i-col span="12">
						<FormItem label="快递费" prop="expressFee">
							<InputNumber v-model="form.expressFee" placeholder="请输入快递费" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>
				<Row>
					<i-col span="12">
						<FormItem label="规格" prop="expressSpec">
							<InputNumber v-model="form.expressSpec" placeholder="请输入规格" style="width: 100%;" />
						</FormItem>

					</i-col>
					<i-col span="12">
						<FormItem label="递增规格" prop="incrementSpec">
							<InputNumber v-model="form.incrementSpec" placeholder="请输入递增规格" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>
				<Row>
					<i-col span="12">
						<FormItem label="递增快递费" prop="incrementFee">
							<InputNumber v-model="form.incrementFee" placeholder="请输入递增快递费" style="width: 100%;" />
						</FormItem>
					</i-col>
					<i-col span="12">
						<FormItem label="包邮条件" prop="freeCondition">
							<InputNumber v-model="form.freeCondition" placeholder="请输入包邮条件" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>
				<Row>
					<i-col span="12">
						<FormItem label="包邮金额" prop="freeMaxPayment">
							<InputNumber v-model="form.freeMaxPayment" placeholder="请输入包邮金额" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>

			</Form>
			<div slot="footer">
				<Button type="text" size="large" @click="closeExpress">取消</Button>
				<Button type="primary" size="large" @click="editExpress" :loading="loading.editExpress">修改</Button>
			</div>
		</Modal>
		<Modal v-model="modal.province" title="添加省" :mask-closable="false" width="1020">
			<div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
				<Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="checkAllProvince">全选</Checkbox>
			</div>
			<Row :gutter="24">
				<CheckboxGroup v-model="checkedProvince" @on-change="checkChange">
					<i-col style="margin-bottom: 10px;" :xs="12" :md="6" :lg="4" v-for="(province, index) in provinceData" :key="index">
						<Checkbox :label="province.label"></Checkbox>
					</i-col>
				</CheckboxGroup>
			</Row>
			<div slot="footer">
				<Button type="text" size="large" @click="closeProvince">取消</Button>
				<Button type="primary" size="large" @click="saveProvinceExpress" :loading="loading.saveProvinceExpress">添加</Button>
			</div>
		</Modal>
		<Modal v-model="modal.add" title="新建模板" :mask-closable="false" width="1020" @on-visible-change="changeModalVisibleResetForm1('editForm', $event)">
			<Form ref="addForm" :model="form" :label-width="120" :rules="validateRules">
				<Row>
					<i-col span="12">
						<FormItem label="物流公司" prop="expressCompany">
							<Select v-model="form.expressCompany" placeholder="请选择物流公司" filterable @on-change="selectCompany">
								<Option value="普通快递">普通快递</Option>
							</Select>
						</FormItem>
					</i-col>
					<i-col span="12">
						<FormItem label="是否包邮" prop="expressFree">

							<Select v-model="form.expressFree" placeholder="是否包邮" filterable clearable>
								<Option v-for="(option, index) in expressFreeSelect" :value="option.value" :key="index">{{option.displayValue}}</Option>
							</Select>

						</FormItem>

					</i-col>
				</Row>
				<Row>
					<i-col span="12">
						<FormItem label="快递费" prop="expressFee">
							<InputNumber v-model="form.expressFee" placeholder="请输入快递费" style="width: 100%;" />
						</FormItem>
					</i-col>
					<i-col span="12">
						<FormItem label="规格" prop="expressSpec">
							<InputNumber v-model="form.expressSpec" placeholder="请输入规格" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>
				<Row>
					<i-col span="12">
						<FormItem label="递增规格" prop="incrementSpec">
							<InputNumber v-model="form.incrementSpec" placeholder="请输入递增规格" style="width: 100%;" />
						</FormItem>
					</i-col>
					<i-col span="12">
						<FormItem label="递增快递费" prop="incrementFee">
							<InputNumber v-model="form.incrementFee" placeholder="请输入递增快递费" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>
				<Row>
					<i-col span="12">
						<FormItem label="包邮条件" prop="freeCondition">
							<InputNumber v-model="form.freeCondition" placeholder="请输入包邮条件" style="width: 100%;" />
						</FormItem>
					</i-col>
					<i-col span="12">
						<FormItem label="包邮金额" prop="freeMaxPayment">
							<InputNumber v-model="form.freeMaxPayment" placeholder="请输入包邮金额" style="width: 100%;" />
						</FormItem>
					</i-col>
				</Row>

			</Form>
			<div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
				<span style="margin-right: 20px;">选择目的地</span>
				<Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="checkAllProvince">全选</Checkbox>
			</div>
			<Row :gutter="24">
				<CheckboxGroup v-model="checkedProvince" @on-change="checkChange">
					<i-col style="margin-bottom: 10px;" :xs="12" :md="6" :lg="4" v-for="(province, index) in provinceData" :key="index">
						<Checkbox :label="province.label"></Checkbox>
					</i-col>
				</CheckboxGroup>
			</Row>
			<div slot="footer">
				<Button type="text" size="large" @click="closeAdd">取消</Button>
				<Button type="primary" size="large" @click="saveExpress" :loading="loading.saveExpress">添加</Button>
			</div>
		</Modal>
	</div>
</template>

<script>
	import * as utils from '@/api/utils-v2'
	import * as ResponseStatus from '@/api/response-status'
	import {
		convertJson
	} from '@/api/express'
	import {
		provinceData
	} from '@/api/province'
	export default {
		name: 'ExpressTemplateItemSetting',
		props: {
			onlyView: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				modal: {
					setting: false,
					add: false,
					edit: false,
					province: false
				},
				dataDictCodes: ['EXPRESS_FREE'],
				dataDictItems: {},
				expressFreeSelect: [],
				loading: {
					saveExpress: false,
					editExpress: false,
					saveProvinceExpress: false
				},
				urls: {
					addUrl: '/express-template-item/admin/save',
					batchAddUrl: '/express-template-item/admin/batch-save',
					editUrl: '/express-template-item/admin/update',
					batchEditUrl: '/express-template-item/admin/batch-update'
				},
				form: {
					templateId: null,
					expressCompany: '普通快递',
					province: null,
					city: null,
					district: null,
					expressFree: null,
					expressFee: null,
					expressSpec: null,
					incrementSpec: null,
					incrementFee: null,
					freeCondition: null,
					freeMaxPayment: null,

				},
				validateRules: {
					templateId: [{
						type: 'integer',
						required: true,
						message: '此项为必须项',
						trigger: 'blur, change'
					}],
					expressCompany: [{
							type: 'string',
							required: true,
							message: '此项为必须项',
							trigger: 'blur'
						},
						{
							type: 'string',
							min: 1,
							max: 255,
							message: '必须1-255个字符',
							trigger: 'blur'
						}
					],
					province: [{
							type: 'string',
							required: true,
							message: '此项为必须项',
							trigger: 'blur'
						},
						{
							type: 'string',
							min: 1,
							max: 50,
							message: '必须1-50个字符',
							trigger: 'blur'
						}
					],
					city: [{
						type: 'string',
						min: 1,
						max: 50,
						message: '必须1-50个字符',
						trigger: 'blur'
					}],
					district: [{
						type: 'string',
						min: 1,
						max: 50,
						message: '必须1-50个字符',
						trigger: 'blur'
					}],
					expressFree: [{
						type: 'integer',
						required: true,
						message: '此项为必须项',
						trigger: 'blur, change'
					}],
					expressFee: [{
						type: 'number',
						required: true,
						message: '此项为必须项',
						trigger: 'blur, change'
					}],
					expressSpec: [{
						type: 'number',
						required: true,
						message: '此项为必须项',
						trigger: 'blur, change'
					}],

				},
				templateId: null,
				expressJson: {},
				provinceData: [],
				checkedProvince: [],
				checkAll: false,
				indeterminate: false,
				checkedExpressCompany: null,
				checkedExpressData: {},
				toEditExpressData: {}
			}
		},
		computed: {},
		mounted() {
			this.provinceData = provinceData
			utils.getDataDict(this.dataDictCodes).then(response => {
				if (response) {
					this.dataDictItems = response
					utils.getSelectDictItems(this, 'EXPRESS_FREE', 'expressFree', 'expressFreeSelect')

				}
			}).catch(error => {
				console.log(error)
			})


		},
		methods: {

			loadExpressTemplateItems(templateId) {
				this.expressJson = {}
				this.templateId = templateId
				utils.doPostJson('/express-template-item/admin/all-cond', {
					templateId: templateId,
					sortColumn: 'createTime',
					sortOrder: 'asc'
				}, {}).then(response => {
					if (response.data.code === ResponseStatus.OK) {
						if (response.data.data.rows.length > 0) {
							this.expressJson = convertJson(response.data.data.rows)
							for (let i = 0, len = this.expressJson[0].expressData.length; i < len; i++) {
								let data = this.expressJson[0].expressData[i];
								this.expressJson[0].expressData[i] = this.getDetailDictItemDisplayValue(data, 'EXPRESS_FREE', 'expressFree')
							}

						}
					} else {
						this.$Message.error(response.data.message)
					}
				}).catch(error => {
					console.log(error)
				})
			},
			getDetailDictItemDisplayValue(expressData, dictCode, formProp) {
				let dictItems = this.dataDictItems[dictCode]

				for (let i = 0, len = dictItems.length; i < len; i++) {
					if (expressData.data[formProp] === dictItems[i].value) {
						expressData.data[formProp] = expressData.data[formProp]
						expressData.data[formProp + 'Val'] = dictItems[i].displayValue
						return expressData;
					}
				}
			},
			removeProvince(expressItemId) { 
				this.$Modal.confirm({
					title: '确认删除吗？',
					content: '确认删除选择的数据吗？',
					onOk: () => {
						utils.doGet("/express-template-item/admin/remove/" + expressItemId, {}).then(response => {
							if (response.data.code === ResponseStatus.OK) {
								this.loadExpressTemplateItems(this.templateId)
								this.provinceData = provinceData
							} else {
								this.$Message.error('稍候再试')
							}
						}).catch(error => {
							console.log(error)
						})
					},
					onCancel: () => {

					}
				})
			},
			showAddProvince(expressItem, data) {
				this.modal.province = true
				this.provinceData = provinceData
				let allExistProvince = []
				// 需要把同一个快递的所有已配置运费的省去除
				expressItem.expressData.forEach(item => {
					item.area.forEach(province => {
						allExistProvince.push(province)
					})
				})
				this.checkedExpressCompany = expressItem.expressCompany
				this.checkedExpressData = data
				for (let i = 0, len = allExistProvince.length; i < len; i++) {
					this.provinceData = this.provinceData.filter(item => {
						return item.label != allExistProvince[i].province
					})
				}
			},
			removeAllProvince(areas) {
				this.$Modal.confirm({
					title: '确认删除所有省吗？',
					content: '确认删除选择的数据吗？',
					onOk: () => {
						let ids = []
						areas.forEach(area => {
							ids.push(area.id)
						})
						utils.doPostJson("/express-template-item/admin/batch-remove", ids, {}).then(response => {
							if (response.data.code === ResponseStatus.OK) {
								this.loadExpressTemplateItems(this.templateId)
								this.provinceData = provinceData
							} else {
								this.$Message.error('稍候再试')
							}
						}).catch(error => {
							console.log(error)
						})
					},
					onCancel: () => {

					}
				})
			},
			closeSetting() {
				this.modal.setting = false
			},
			checkAllProvince() {
				if (this.checkAll) {
					this.checkedProvince = []
				} else {
					this.provinceData.forEach(province => {
						this.checkedProvince.push(province.label)
					})
				}
				this.checkAll = !this.checkAll
				this.indeterminate = false
			},
			checkChange() {
				if (this.checkedProvince.length > 0 && this.checkedProvince.length < this.provinceData.length) {
					this.indeterminate = true
				} else {
					this.indeterminate = false
				}
			},
			showEdit(expressCompany, expressData) {
				this.modal.edit = true
				this.toEditExpressData = expressData
				this.form.templateId = this.templateId
				this.form.expressCompany = expressCompany
				this.form.expressFree = expressData.data.expressFree,
				this.form.expressFreeValue = expressData.data.expressFreeVal
				this.form.expressFee = expressData.data.expressFee,
				this.form.expressSpec = expressData.data.expressSpec,
				this.form.incrementSpec = expressData.data.incrementSpec,
				this.form.incrementFee = expressData.data.incrementFee,
				this.form.freeMaxPayment = expressData.data.freeMaxPayment,
				this.form.freeCondition = expressData.data.freeCondition
			},
			showAddExpressItem() {
				this.modal.add = true
				this.selectCompany(this.form.expressCompany)
			},
			changeModalVisibleResetForm(formRef, visible) {
				if (!visible) {
					this.$refs[formRef].resetFields()
				}
			},
			changeModalVisibleResetForm1(formRef, visible) {
				if (!visible) {
					this.$refs[formRef].resetFields()
				}
				this.checkedProvince = []
				this.indeterminate = false
			},
			resetFormCancelModal(formRef, modal) {
				this.modal[modal] = false
				this.$refs[formRef].resetFields()
			},
			add() {
				this.$emit('add')
			},
			edit() {
				this.$emit('edit')
			},
			saveProvinceExpress() {
				if (this.checkedProvince.length === 0) {
					this.$Message.warning('请先选择需要添加的省')
				}
				let data = []
				this.checkedProvince.forEach(province => {
					data.push({
						templateId: this.templateId,
						expressCompany: this.checkedExpressCompany,
						province: province,
						expressFree: this.checkedExpressData.expressFree,
						expressFee: this.checkedExpressData.expressFee,
						expressSpec: this.checkedExpressData.expressSpec,
						incrementSpec: this.checkedExpressData.incrementSpec,
						incrementFee: this.checkedExpressData.incrementFee,
						freeMaxPayment: this.checkedExpressData.freeMaxPayment,
						freeCondition: this.checkedExpressData.freeCondition
					})
				})
				utils.doPostJson('/express-template-item/admin/batch-save', data, {}).then(response => {
					if (response.data.code === ResponseStatus.OK) {
						this.$Message.success('添加成功')
						this.modal.province = false
						this.checkedProvince = []
						this.loadExpressTemplateItems(this.templateId)
						this.provinceData = provinceData
					} else {
						this.$Message.error('添加失败，请稍候再试')
					}
				}).catch(error => {
					console.log(error)
				})
			},
			selectCompany(expressCompany) {
				if (expressCompany) {
					this.provinceData = provinceData
					let allExistProvince = []
					// 需要把同一个快递的所有已配置运费的省去除
					for (let i = 0, len = this.expressJson.length; i < len; i++) {
						if (this.expressJson[i].expressCompany === expressCompany) {
							this.expressJson[i].expressData.forEach(expressData => {
								expressData.area.forEach(area => {
									allExistProvince.push(area)
								})
							})
							break
						}
					}
					for (let i = 0, len = allExistProvince.length; i < len; i++) {
						this.provinceData = this.provinceData.filter(item => {
							return item.label != allExistProvince[i].province
						})
					}
				}
				this.checkedProvince = []
				this.indeterminate = false
			},
			saveExpress() {
				this.$refs.addForm.validate(valid => {
					if (valid) {
						if (this.checkedProvince.length === 0) {
							this.$Message.warning('请先选择需要添加的省')
							return
						}
						let data = []
						this.checkedProvince.forEach(province => {
							data.push({
								templateId: this.templateId,
								province: province,
								expressCompany: this.form.expressCompany,
								expressFree: this.form.expressFree,
								expressFee: this.form.expressFee,
								expressSpec: this.form.expressSpec,
								incrementSpec: this.form.incrementSpec,
								incrementFee: this.form.incrementFee,
								freeMaxPayment: this.form.freeMaxPayment,
								freeCondition: this.form.freeCondition
							})
						})
						this.loading.saveExpress = true
						utils.doPostJson('/express-template-item/admin/batch-save', data, {}).then(response => {
							if (response.data.code === ResponseStatus.OK) {
								this.$Message.success('新建运费模板成功')
								this.modal.add = false
								this.loadExpressTemplateItems(this.templateId)
								this.loading.saveExpress = false
								this.checkedProvince = []
								this.indeterminate = false
							} else {
								this.$Message.error('添加失败，请稍候再试')
								this.loading.saveExpress = false
							}
						}).catch(error => {
							console.log(error)
						})
					}
				})
			},
			editExpress() {
				this.$refs.editForm.validate(valid => {
					if (valid) {
						let data = []
						this.toEditExpressData.area.forEach(area => {
							data.push({
								id: area.id,
								templateId: this.templateId,
								province: area.province,
								expressCompany: this.form.expressCompany,
								expressFree: this.form.expressFree,
								expressFee: this.form.expressFee,
								expressSpec: this.form.expressSpec,
								incrementSpec: this.form.incrementSpec,
								incrementFee: this.form.incrementFee,
								freeMaxPayment: this.form.freeMaxPayment,
								freeCondition: this.form.freeCondition
							})
						})
						this.loading.editExpress = true
						utils.doPostJson('/express-template-item/admin/batch-update', data, {}).then(response => {
							if (response.data.code === ResponseStatus.OK) {
								this.$Message.success('修改成功')
								this.modal.edit = false
								this.checkedProvince = []
								this.loadExpressTemplateItems(this.templateId)
								this.loading.editExpress = false
							} else {
								this.$Message.error('添加失败，请稍候再试')
								this.loading.editExpress = false
							}
						}).catch(error => {
							console.log(error)
						})
					}
				})
			},
			closeProvince() {
				this.modal.province = false
				this.checkedProvince = []
				this.indeterminate = false
				this.checkAll = false
			},
			closeAdd() {
				this.modal.add = false
				this.checkedProvince = []
				this.indeterminate = false
				this.$refs.addForm.resetFields()
			},
			closeExpress() {
				this.modal.edit = false
				this.$refs.editForm.resetFields()
			}
		}
	}
</script>

<style>
</style>
